package com.zeng.sys.authmd.restfulmodule.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.zeng.sys.authmd.apimodule.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class TokenUtil {

    // code : user
    private static Map<String, UserVo> loginMap = new ConcurrentHashMap<>();

    // token:code
    private static Map<String, String> tokenCache = new ConcurrentHashMap<>();

    // 确保一个code 对应一个token
   public String getToken(UserVo user,Long expiresTime) {
        String token= null;
        token= JWT.create().withAudience(user.getCode()).withExpiresAt(new Date(expiresTime)).withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(user.getUserPw()));
       if (tokenCache.containsValue(user.getCode())) {
           Set<String> keys = tokenCache.keySet();
           Iterator<String> iterator = keys.iterator();
           while (iterator.hasNext()) {
               String next = iterator.next();
               next.equals(user.getCode());
               iterator.remove();
           }
       }
       tokenCache.put(token, user.getCode());
       log.info("当前token缓存大小:[{}]", tokenCache.size());
        return token;
    }
    public static UserVo getLoginUser(String code) {
        return loginMap.get(code);
    }

    public static void addLoginUser(String code, UserVo user) {
        loginMap.put(code, user);
    }

    public static UserVo removeLoginUser(String code) {
        return loginMap.remove(code);
    }

    public static boolean isToken(String token) {
        if (token == null) {
            return false;
        }
        return tokenCache.containsKey(token);
    }

    public static String getCodeInTokenCache(String token) {

        return tokenCache.get(token);
    }


    public static boolean removeToken(String token) {
        return tokenCache.remove(token) != null;
    }

    public static UserVo getUserByToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (StringUtils.isNotEmpty(token)) {
            String userCode = tokenCache.get(token);
            if (StringUtils.isEmpty(userCode)) {
                return null;
            }
            UserVo userVo = loginMap.get(userCode);
            return userVo;
        }
        return null;
    }

}
